package mongodb

import (
	"fmt"
	"gitee.com/dennis-kk/service-box-go/util/errors"
)

//mongo driver go 封装，方便用户进行初始化，collection管理等

const (
	//mongoAuthUri mongodb user:passwd@ip:port[,ip:port]/db?authSource=db
	mongoAuthUri = "mongodb://%s:%s@%s/%s?authSource=%s&authMechanism=SCRAM-SHA-1"
	//mongoUri mongodb ip:port[,ip:port]/db
	mongoUri = "mongodb://%s/%s"
)

type (
	Options struct {
		// User 用户名
		User string `yaml:"user"`
		// PassWord 密码
		Password string `yaml:"password"`
		// DB 数据库名
		DB string `yaml:"db"`
		//Mongos mongo 集群节点地址
		Mongos []string `yaml:"mongos"`
	}

	Option func(o *Options)
)

// genMongoUri 将mongo 配置 转化为uri
func (o *Options) genMongoUri() (string, error) {
	//检查 mongo nodes 节点地址
	if len(o.Mongos) < 1 {
		return "", errors.MongoConfigError
	}

	// 检查 db 配置
	if len(o.DB) == 0 {
		return "", errors.MongoConfigError
	}

	// 根据mongo 节点生成host 配置
	hosts := ""
	for idx, host := range o.Mongos {
		if idx != 0 {
			hosts += ","
		}
		hosts += host
	}
	// 根据是否配置用户选择拼接方式
	var uri string
	if len(o.User) == 0 {
		uri = fmt.Sprintf(mongoUri, hosts, o.DB)
	} else {
		uri = fmt.Sprintf(mongoAuthUri, o.User, o.Password, hosts, o.DB, o.DB)
	}

	return uri, nil
}
